package Utils.data;


import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;

/**
 * Base64工具类
 *
 * @author d11yu
 */
public class Base64Utils {
    private Base64 base64;
    private static Base64Utils instance;

    private Base64Utils() {
        base64 = new Base64();
    }

    public static Base64Utils getInstance() {
        if (instance == null) {
            instance = new Base64Utils();
        }
        return instance;
    }

    /**
     * Base64加密
     *
     * @param content 待加密的字符串
     * @return 返回加密的字符串
     */
    public String encode(String content) {
        return encode(content, "UTF-8");
    }

    /**
     * Base64加密
     *
     * @param content 待加密的字符串
     * @param charset 字符串编码，默认是UTF-8
     * @return 返回加密的字符串
     */
    public String encode(String content, String charset) {
        try {
            return  base64.encodeToString(content.getBytes(charset));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * base64解码
     * @param content 待解码字符串
     * @return 返回已解码的字符串
     */
    public String decode(String content) {
        return decode(content, "UTF-8");
    }

    /**
     * base64解码
     * @param content 待解码字符串
     * @param charset 字符串编码，默认是UTF-8
     * @return 返回已解码的字符串
     */
    public String decode(String content, String charset) {
        try {
            return new String(base64.decode(content), charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
